package com.coisini.service.impl;

import com.coisini.constant.MessageConstant;
import com.coisini.constant.PasswordConstant;
import com.coisini.constant.StatusConstant;
import com.coisini.context.BaseContext;
import com.coisini.dto.EmployeeDTO;
import com.coisini.dto.EmployeeLoginDTO;
import com.coisini.dto.EmployeePageQueryDTO;
import com.coisini.dto.PasswordEditDTO;
import com.coisini.entity.Employee;
import com.coisini.exception.AccountLockedException;
import com.coisini.exception.AccountNotFoundException;
import com.coisini.exception.PasswordErrorException;
import com.coisini.mapper.EmployeeMapper;
import com.coisini.result.PageResult;
import com.coisini.service.EmployeeService;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /*
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        //2.1 账号不存在
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //2.2 密码比对
        //数据库中已经对密码进行MD加密了，所以需要将接收的密码进行进行之后比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * 新增员工
     * @param employeeDTO
     */
    @Override
    public void save(EmployeeDTO employeeDTO) {
        Employee employee=new Employee();

        //使用属性拷贝，将封装的EmployeeDTO类中属性值拷贝到Employee这个对象上
        BeanUtils.copyProperties(employeeDTO,employee);

        //设值Employee实体类中的其他属性值

        //1.设置密码 进行MD5加密
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()) );
        //2.设置状态 默认状态为正常状态
        employee.setStatus(StatusConstant.ENABLE);
        //3.设置创建时间修改时间
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
        //4.设置创建人id，修改人id --> 即当前登录人的id
        //客户端每次发起的一个请求就是一个独立的线程
        //将线程的id获取出来
//        employee.setCreateUser(BaseContext.getCurrentId());
//        employee.setUpdateUser(BaseContext.getCurrentId());


        //调用持久层mapper层进行与数据库操作
        employeeMapper.insert(employee);

    }

    /**
     * 员工分页查询
     * @param employeePageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(EmployeePageQueryDTO employeePageQueryDTO) {
        //设置分页查询条件
        PageHelper.startPage(employeePageQueryDTO.getPage(),employeePageQueryDTO.getPageSize());
        //调用mapper方法进行查询
      List<Employee> employeeList = employeeMapper.pageQuery(employeePageQueryDTO);
        Page<Employee> page= (Page<Employee>) employeeList;
        //封装为PageResult 分页查询结果返回
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 启用/禁用员工账号
     * @param id
     * @param status
     */
    @Override
    public void changeStatus(Integer status, Long id) {
        //想要对数据库执行的语句为：
        // update employee set status = ? where id = ?

        //在mapper层中使用一个update接口，完成动态修改员工的数据

        //构建一个员工对象
        Employee employee = Employee.builder()
                .status(status)
                .id(id)
               // .updateUser(BaseContext.getCurrentId())
                //.updateTime(LocalDateTime.now())
                .build();

        //调用mapper接口
        employeeMapper.update(employee);
    }


    /**
     * 根据id查询员工
     * @param id
     * @return
     */
    @Override
    public Employee getById(Long id) {

        Employee employee= employeeMapper.getById(id);
        employee.setPassword("****"); //不展示密码
        return employee;
    }

    /**
     * 编辑员工信息
     * @param employeeDTO
     */
    @Override
    public void update(EmployeeDTO employeeDTO) {
        //创建Employee对象
        Employee employee=new Employee();
        //使用属性拷贝
        BeanUtils.copyProperties(employeeDTO,employee);

        //操作 编辑员工功能，需要修改两个数据
        /*
        // 1.修改人的id
        employee.setUpdateUser(BaseContext.getCurrentId());
        // 2.更新修改时间
        employee.setUpdateTime(LocalDateTime.now());

         */

        //调用mapper接口中动态修改员工的接口
        employeeMapper.update(employee);
    }

    /**
     * 修改密码
     * @param passwordEditDTO
     */
    @Override
    public void editPassword(PasswordEditDTO passwordEditDTO) {
        //将新密码取出
        String password = passwordEditDTO.getNewPassword();
        //将密码进行MD5加密
        password=DigestUtils.md5DigestAsHex(password.getBytes());
        //取出id
        Long id = passwordEditDTO.getEmpId();

        //构建一个Employee对象
        Employee employee = Employee.builder()
                .password(password)
                .updateTime(LocalDateTime.now())
                .build();

        employee.setId(BaseContext.getCurrentId());
        System.out.println(employee);
        employeeMapper.update(employee);
    }
}
